package com.gemantic.task.util;

import java.util.List;
import java.util.concurrent.CountDownLatch;

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import com.gemantic.task.config.ThreadPoolConfig;
import com.gemantic.task.function.Runnable1;
import com.gemantic.task.function.Runnable2;
import com.gemantic.task.function.Runnable3;


public final class ThreadPoolUtil {
    private ThreadPoolUtil() {
    }

    private static ThreadPoolTaskExecutor getExecutor() {
        return SpringUtils.getBean(ThreadPoolConfig.THREAD_POOL_NAME,ThreadPoolTaskExecutor.class);
    }

    public static void execute(Runnable runnable) {
        getExecutor().execute(() -> {
            try {
                runnable.run();
            } catch (Exception var2) {
                ExceptionUtil.getStackTrace(var2);
            }
        });
    }

    public static <T> void execute(Runnable1<T> runnable, T t1) {
        execute(() -> {
            runnable.run(t1);
        });
    }

    public static <T1, T2> void execute(Runnable2<T1, T2> runnable, T1 t1, T2 t2) {
        execute(() -> {
            runnable.run(t1, t2);
        });
    }

    public static <T1, T2, T3> void execute(Runnable3<T1, T2, T3> runnable, T1 t1, T2 t2, T3 t3) {
        execute(() -> {
            runnable.run(t1, t2, t3);
        });
    }

    public static <T1, T2> void execute(Runnable3<T1, T2, Integer> runnable, List<T1> list, T2 t2, boolean await) {
        if (!CollectionUtils.isEmpty(list)) {
            CountDownLatch countDownLatch = new CountDownLatch(list.size());

            for(int i = 0; i < list.size(); ++i) {
                execute((item, latch, index) -> {
                    latch.countDown();
                    runnable.run(item, t2, index);
                }, list.get(i), countDownLatch, i);
            }

            if (await) {
                try {
                    countDownLatch.await();
                } catch (InterruptedException var6) {
                    Thread.currentThread().interrupt();
                }
            }

        }
    }

}
